package com.hnluchuan.bmjlearning.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;
import org.apache.commons.lang3.StringUtils;
	
import com.hnluchuan.core.dao.BaseDAO;
import com.hnluchuan.bmjlearning.model.Sms;
import com.hnluchuan.bmjlearning.dto.SmsDTO;
import com.hnluchuan.core.support.Page;

@Repository
public class SmsDAO extends BaseDAO<Sms> {

    public List<Sms> find(SmsDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Sms n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (StringUtils.isNotBlank(dto.getMobile())) {
            hql.append(" and n.mobile = ? ");
            paras.add(dto.getMobile());
        }		
        if (StringUtils.isNotBlank(dto.getCode())) {
            hql.append(" and n.code = ? ");
            paras.add(dto.getCode());
        }		
        if (dto.getType() != null) {
            hql.append(" and n.type = ? ");
            paras.add(dto.getType());
        }
        if (dto.getUsed() != null) {
            hql.append(" and n.used = ? ");
            paras.add(dto.getUsed());
        }
        hql.append(" order by n.created desc ");
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public Sms findOne(SmsDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<Sms> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }
    
    @Override
	public Long create(Sms sms) {
	    if (sms.getCreated() == null) {    
	        sms.setCreated(new Date());
	    }    
		return super.create(sms);
	}

	@Override
	public void update(Sms sms) {
		super.update(sms);
	}

    public Sms findByExpireDate(Date date) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Sms n where n.expireDate > ? ");
        paras.add(date);
        return super.findOne(hql.toString(), paras.toArray());
    }

    public Sms findLastOneByMobile(String mobile, String code) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Sms n where n.mobile = ? and code = ? and n.expireDate > ? order by n.expireDate desc " );
        paras.add(mobile);
        paras.add(code);
        paras.add(new Date());
        return super.findOne(hql.toString(), paras.toArray());
    }
    
}
